#!/usr/bin/env python
# encoding: utf-8
"""
Banner.py

Created by Manabu Terada on 2009-09-24.
Copyright (c) 2009 CMScom. All rights reserved.
"""
from AccessControl import ClassSecurityInfo
from ComputedAttribute import ComputedAttribute
from zope import interface

from Products.Archetypes.atapi import *
from Products.CMFCore.utils import getToolByName

from Products.ATContentTypes.content.link import ATLink
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.configuration import zconf
from Products.CMFCore.permissions import View, ModifyPortalContent

from c2.site.icos09 import icos09MessageFactory as _
from c2.site.icos09.content.interfaces import IBanner
from c2.site.icos09.config import *
from c2.site.icos09.swfHeaderData import analyseContent

schema = Schema((
    ImageField('image',
           required=False,
           swallowResizeExceptions = zconf.swallowImageResizeExceptions.enable,
           pil_quality = zconf.pil_config.quality,
           pil_resize_algo = zconf.pil_config.resize_algo,
           max_size = zconf.ATImage.max_image_dimension,
           sizes= {
                   'mini'    :  (400, 400),
                   'banner'  :  (230, 86),
                   'fortop'  :  (165, 62),
                   'square'  :  (50,50),
                  },
           widget=ImageWidget(label='image',
                              description='',
                              label_msgid='image',
                              description_msgid='image_help',
                              i18n_domain = "icos09"
                              ),
            ),
    StringField('image_alt',
            required=False,
            widget=StringWidget(label='image_alt',
                            description='',
                            label_msgid = "image_alt",
                            description_msgid = 'image_alt_help',
                            i18n_domain = "icos09",
                            size=40
                            ),
            ),
            

    BooleanField(
        required=False,
        name='useFlash',
        widget=BooleanField._properties['widget'](
            label='Use Flash',
            label_msgid='use_flash',
            description_msgid = 'use_flash_help',
            i18n_domain='icos09',
        ),
    ),
    IntegerField('flash_h',
        required=False,
        widget=IntegerWidget(label='flash_h',
                        description='',
                        label_msgid='flash_h',
                        description_msgid='flash_h_help',
                        i18n_domain ='icos09',
                        )),
    IntegerField('flash_w',
        required=False,
        widget=IntegerWidget(label='flash_w',
                        description='',
                        label_msgid='flash_w',
                        description_msgid='flash_w_help',
                        i18n_domain ='icos09',
                        )),
    IntegerField('flash_v',
        required=False,
        widget=IntegerWidget(label='flash_v',
                        description='',
                        label_msgid='flash_v',
                        description_msgid='flash_v_help',
                        i18n_domain ='icos09',
                        )),
    # Flashファイル
    FileField('flash',
             required=False,
             searchable=False,
             storage=AnnotationStorage(migrate=True),
             widget=FileWidget(label='flash',
                       description='',
                       label_msgid='flash',
                       description_msgid ='flash_help',
                       i18n_domain='icos09',)),
    # リンク先を別窓に表示
    BooleanField('is_new_window',
            required=False,
            searchable=False,
            widget=BooleanWidget(label='is_new_window',
                            description='',
                            label_msgid = "is_new_window",
                            description_msgid = 'is_new_window_help',
                            i18n_domain = "icos09",
                            ),
            ),
),)

banner_schema = getattr(ATLink, 'schema', Schema(())).copy() + schema.copy()
# banner_schema['relatedItems'].widget.visible['edit'] = 'invisible'
finalizeATCTSchema(banner_schema)

class Banner(ATLink):
    """
    """
    security = ClassSecurityInfo()
    interface.implements(IBanner)
    schema = banner_schema
    
    meta_type = "Banner"
    _at_rename_after_creation = True
    
    def getSwf_tag(self):
        size_height = self.getFlash_h()
        size_width = self.getFlash_w()
        version = self.getFlash_v()
        uid = self.UID()
        swf_path = "%s/get_flash_file" % self.absolute_url()
        
        swf_tag_tmplate = """
              <div id="%s">
              <script type="text/javascript">
                var flashVars = {}
                var parms = {
                wmode :"transparent"
                }
                swfobject.embedSWF("%s", "%s", "%s", "%s", "%s","",flashVars,parms, {menu:"false"}, {})
              </script>
              </div>""" % (uid, swf_path, uid, size_width, size_height, version)
        return swf_tag_tmplate

    security.declareProtected(View, 'tag')
    def tag(self, **kwargs):
        """Generate image tag using the api of the ImageField
        """
        if not self.getUseFlash():
            if kwargs.get('cls', ''):
                kwargs['class'] = kwargs['cls']
                del kwargs['cls']
            kwargs['alt'] = self.image_alt
            return self.getField('image').tag(self, **kwargs)
        else:
            return self.getSwf_tag()

    security.declareProtected(View, 'getSize')
    def getSize(self, scale=None):
        field = self.getField('image')
        return field.getSize(self, scale=scale)

    security.declareProtected(View, 'getWidth')
    def getWidth(self, scale=None):
        return self.getSize(scale)[0]

    security.declareProtected(View, 'getHeight')
    def getHeight(self, scale=None):
        return self.getSize(scale)[1]

    width = ComputedAttribute(getWidth, 1)
    height = ComputedAttribute(getHeight, 1)
    
    security.declareProtected(ModifyPortalContent, 'setFlash')
    def setFlash(self, value, **kwargs):
        """Saves file and stores flash informations (size, flash version)"""
        if value and not isinstance(value, str):
            value.seek(0) # rewind
            field=self.getField('flash')
            field.set(self,value,**kwargs)
            value.seek(0)
            tags = analyseContent(value.read(1024))
            self.setFlash_w(tags['width'])
            self.setFlash_h(tags['height'])
            self.setFlash_v(tags['flashversion'])
        elif value and isinstance(value, str):
            field1=self.getField('flash')
            field1.set(self, '', **kwargs)
            self.setFlash_w(0)
            self.setFlash_h(0)
            self.setFlash_v(0)

    security.declareProtected(View, 'get_flash_file')
    def get_flash_file(self, REQUEST=None, RESPONSE=None, *args, **kwargs):
        """Download the file (use default index_html)
        """
        if REQUEST is None:
           REQUEST = self.REQUEST
        if RESPONSE is None:
           RESPONSE = REQUEST.RESPONSE
        RESPONSE.setHeader("Content-Type", "application/x-shockwave-flash")
        field = self.getField('flash')
        return field.get(self, raw=True)

    # リンク先を別窓に表示
    def is_new_win(self):
        try: # インスタンス生成時のエラー回避
            is_new = self.aq_inner.is_new_window
        except AttributeError:
            return False
        return is_new

registerType(Banner, PROJECTNAME)
